(in-package :pollster)

(cl-interpol:enable-interpol-syntax)

;; FIXME: use this to determine the printed version
(defparameter *version* "0.1")

(defmacro with-html (&body body)
  `(with-html-output-to-string (*standard-output* nil :prologue t)
     ,@body))


(defun get-id ()
  "Get the poll id from either a parameter or the database"
  (or (parameter "id")
      (current-poll-id)))

(defun front-page ()
  (let ((id (get-id)))
    (with-html
      (:html (:head (:title "Pollster")
		    (:link :rel "stylesheet" :type "text/css"
			   :href "/pollster/style.css"))
	     (:body
	      (:div :style "text-align: center;"
		    (:img :src "/pollster/logo.png")
		    (:h1 (esc (get-poll-title id)))
		    (:form :method "post"
			   :action (format nil "/tbnl/vote.tbnl?id=~D" id)
			   (:div :style "text-align: left; margin-left: 40%;"
				 (print-poll-choices id))
			   (:input :type "submit" :value "Vote"))
		    (:p (:a :href (format nil "/tbnl/results.tbnl?id=~D" id)
			    "View results") (:br)
			(:a :href "/tbnl/create-poll.tbnl"
			    "Create poll"))))))))

(defun vote ()
  (let ((id (get-id)))
    (record-vote id)
    (with-html
      (:html (:head (:title "Pollster | Vote cast"))
	     (:body (:h1 "Vote cast")
		    (:p "Your vote has been recorded, for real this
time, and it is now sitting in our database, yes our nice MySQL
database, as a couple of integers and assorted auxilliary data
structures which are as alien to me as anything that I know about only
from having read about them in my algorithms textbook. But I'm
rambling. Here, for your odd pleasure, is a tabulation of all the
votes:")
		    (print-poll-results id)
		    (:p (:a :href (format nil
				    "/tbnl/pollster-front-page.tbnl?id=~D" id)
			    "Go back to voting page")))))))

(defun view-results ()
  (let ((id (get-id)))
    (with-html
      (:html (:head (:title "Pollster | Viewing results"))
	     (:body (:h1 (esc (get-poll-title id)))
		    (print-poll-results id))))))

(defun create-poll ()
  (with-html
    (:html (:head (:title "Pollster | Create poll"))
	   (:body (:h1 "Create poll")
		  (:form :method "post" :action "/tbnl/do-create-poll.tbnl"
			 (:table
			  (:tr (:td "Poll title")
			       (:td (:input :type "text" :name "question"
					    :size "80")))
			  (:tr (:td "Choices, one per line")
			       (:td (:textarea :rows "20" :cols "80"
					       :name "choices" ""))))
			 (:input :type "submit" :value "Create poll"))))))

(setq *dispatch-table*
        (nconc
	 (mapcar (lambda (args)
                   (apply #'create-prefix-dispatcher args))
                 '(("/tbnl/pollster-front-page.tbnl" front-page)
		   ("/tbnl/vote.tbnl" vote)
		   ("/tbnl/results.tbnl" view-results)
		   ("/tbnl/create-poll.tbnl" create-poll)
		   ("/tbnl/do-create-poll.tbnl" do-create-poll)))
	 (list #'default-dispatcher)))

;(start-tbnl)
;(stop-tbnl)